#include "export.h"
#include "images.h"
#include "months.h"
#include "journal.h"

char *elog_exp_ss = NULL;
char **elog_exp_replace = NULL;
char **elog_exp_with = NULL;	//replace is a list of things to replace with
//"with".
char *elog_exp_stdout = NULL;

/*
Links need to be done before the replaces are done on the main text...

*/

int __exp_html_latex(const char *file, const char *dest, const char *path)
{
	char *full;
	elog_sp_cat(&full, path, "/", file, NULL);
	struct elog_xml_doc *doc = elog_xml_open(full, 0);
	free(full);
	if (doc) {
		if (!(doc->handle)) {
			elog_xml_doc_free(doc);
			return 2;
		}
	} else
		return 2;
	unsigned int len;
	char *txt = elog_io_readRestofFile(doc->handle, &len);
	if (elog_journ_current()->settings->encryption[0] == 'A')
		decryptText(txt, len);
	elog_io_close(doc->handle);
	txt[len - 1] = '\0';

	char *txt_bk;
	elog_sp_cat(&txt_bk, txt, NULL);

	int c;
	for (c = 0; elog_exp_replace[c]; ++c) {
		char *txt_t;
		txt_t =
		    elog_sp_strReplace(txt, elog_exp_replace[c],
				       elog_exp_with[c]);

		free(txt);
		txt = txt_t;
	}

	char *output = elog_exp_ss;
	char *output1 = elog_sp_strReplace(output, "%t", doc->subject);

	output =
	    elog_sp_strReplace(output1, "%m",
			       elog_img_name_smiley(doc->mood));
	free(output1);
	output1 =
	    elog_sp_strReplace(output, "%w",
			       elog_img_name_weather(doc->weather));

	char *date;
	char *day, *month, *year;
	day = elog_sp_shortToString(doc->day);
	month = (char *) elog_mnth_day(doc->month);
	year = elog_sp_shortToString(doc->year);

	elog_sp_cat(&date, "The ", day, elog_mnth_day(doc->day), " of ",
		    month, ", ", year, NULL);
	free(day);
	free(year);

	char *tmp = elog_sp_strReplace(output1, "%d", date);
	free(date);
	free(output1);
	output1 = tmp;


	/*Pull out the link line */
	char *start = strstr(output1, "%%");
	if (!start) {
		elog_err_print("Bad layout file for export\n");
		elog_xml_doc_free(doc);
		return 1;
	}
	start = &(start[1]);
	char *end = strstr(start, "%%");
	if (!end) {
		elog_err_print("Bad layout file for export\n");
		elog_xml_doc_free(doc);
		return 1;
	}
	end = end - (1 * (sizeof *end));	//backing out one
	char *line = malloc(end - start + 1 * (sizeof *end));
	strncpy(line, start, end - start);
	line[end - start] = '\0';

	char *link_lines = malloc(sizeof *link_lines);	//start value, for sp_cat
	link_lines[0] = '\0';

	for (c = 0; doc->links[c] != NULL; ++c) {
		int start, end;
		start = doc->links[c]->start;
		end = doc->links[c]->end;
		if (start > end)	//if they're backwards
		{
			start = doc->links[c]->end;
			end = doc->links[c]->start;
		}

		char *title = malloc((sizeof *title) * (end - start + 1));
		strncpy(title, &(txt_bk[start]), end - start);
		title[end - start] = '\0';

		char *href1 =
		    elog_sp_strReplace(doc->links[c]->href, ".dry",
				       ".html");
		char *href;
		elog_sp_cat(&href, "../../../", strstr(href1, "/"), NULL);
		elog_sp_removeRepeats(href, '/');

		free(href1);

		char *cur = elog_sp_strReplace(line, "%link", title);
		char *cur1 = elog_sp_strReplace(cur, "%href", href);
		char *tmp;
		elog_sp_cat(&tmp, link_lines, cur1, NULL);
		free(link_lines);
		link_lines = tmp;
		free(cur);
		free(cur1);
		free(title);
		free(href);
	}


	output = elog_sp_strReplace(output1, line, link_lines);
	free(output1);
	output1 = elog_sp_strReplace(output, "%%", "");
	free(output);
	output = elog_sp_strReplace(output1, "%b", txt);
	free(output1);
	output1 = output;
	free(line);
	/*done editing links */

	char *new_name = elog_sp_strReplace(file, ".dry", ".html");

	if (elog_exp_stdout) {
		char *tmp = elog_exp_stdout;
		if (tmp == ELOG_ERROR)
			tmp = NULL;

		elog_sp_cat(&elog_exp_stdout, output1, "\n", tmp, NULL);
		if (tmp)
			free(tmp);
	} else {
		char *path_;
		elog_sp_cat(&path_, dest, "/", new_name, NULL);
		struct elog_io_file *f =
		    elog_io_initialize(path_, ELOG_IO_WRITE);
		if (f) {
			elog_io_writeLine(f, output1, 0);
			elog_io_close(f);
		} else
			elog_err_print_console
			    ("Error opening file in exports.c write\n");

		free(path_);
	}



	free(output1);
	free(txt_bk);
	free(txt);
	elog_xml_doc_free(doc);
	return 0;
}


void __exp_html_latex_do(struct elog_io_dir *dir, const char *dest,
			 const char *path)
{
	int j;
	int c = 0;
	for (j = 0; dir->dir[j] != NULL; ++j) {
		char *file;
		elog_sp_cat(&file, dir->path, dir->dir[j], NULL);
		if (dir->dir[j][0] != '/') {
			char *full;
			elog_sp_cat(&full, dir->path, dir->dir[j], NULL);

			__exp_html_latex(full, dest, path);

		} else {
			char *full;
			elog_sp_cat(&full, dir->path, &(dir->dir[j][3]),
				    NULL);
			__exp_html_latex_do(dir->subDir[c], dest, path);
			++c;
		}
	}
}

char *elog_exp_html(const char *dest, int style, ...)
{
	switch (style) {
	case ELOG_EXP_HTML_STYLE_LATEX:
		{
			char *path;
			elog_sp_cat(&path, DATADIR,
				    "/ejourn/page/latex.html", NULL);
			struct elog_io_file *f =
			    elog_io_initialize(path, ELOG_IO_READ);

			if (!f) {
				elog_err_print
				    ("Error exporting, failed to open ejourn/page/latex.html\n");
				return NULL;
			}
			int len;
			elog_exp_ss = elog_io_readRestofFile(f, &len);
			elog_exp_ss[len - 1] = '\0';	//necessary

			free(path);
			elog_io_close(f);

			break;
		}
	case ELOG_EXP_STYLE_USER:
		{
			va_list(ap);
			va_start(ap, style);
			char *style = va_arg(ap, char *);

			va_end(ap);

			char *path;
			elog_sp_cat(&path, getenv("HOME"), _ELOG_CONFIG,
				    _ELOG_EXPORTS, "/", style, NULL);
			struct elog_io_file *f =
			    elog_io_initialize(path, ELOG_IO_READ);
			if (!f) {
				elog_err_print
				    ("Error, unable to open export file\n");
				return NULL;
			}
			int len;
			elog_exp_ss = elog_io_readRestofFile(f, &len);
			elog_exp_ss[len - 1] = '\0';
			elog_io_close(f);
			free(path);

			break;
		}
	}
	struct elog_io_dir *dir =
	    elog_io_recurseDir(elog_set_get_str("path"), "");
	/*get replacements from file */
	char *start = strstr(elog_exp_ss, "%%");

	char *end = strstr(&(start[2]), "%%");
	char *tmp = elog_exp_ss;
	elog_exp_ss = &(end[3]);

	elog_sp_cat(&elog_exp_ss, &(end[3]), NULL);


	start = &(start[3]);
	end[0] = '\0';
	elog_exp_replace = malloc((sizeof *elog_exp_replace) * 256);
	elog_exp_with = malloc((sizeof *elog_exp_with) * 256);
	char **list = elog_sp_breakToArr(start, '\n');
	int c = 0;
	while (list[c]) {
		char **tokens = elog_sp_breakToArr(list[c], ':');
		if (tokens) {
			printf("%s=%s\n", tokens[0], tokens[1]);
			if (tokens[0][0] == '\\' && tokens[0][1] == 'n')
				elog_sp_cat(&(elog_exp_replace[c]), "\n",
					    NULL);
			else if (tokens[0][0] == '\\'
				 && tokens[0][1] == 's')
				elog_sp_cat(&(elog_exp_replace[c]), " ",
					    NULL);
			else if (tokens[0][0] == '\\'
				 && tokens[0][1] == 't')
				elog_sp_cat(&(elog_exp_replace[c]), "\t",
					    NULL);
			else
				elog_exp_replace[c] = tokens[0];

			if (tokens[1][0] == '\\' && tokens[1][1] == 'n')
				elog_sp_cat(&(elog_exp_with[c]), "\n",
					    NULL);
			else if (tokens[1][0] == '\\'
				 && tokens[1][1] == 's')
				elog_sp_cat(&(elog_exp_replace[c]), " ",
					    NULL);
			else if (tokens[1][0] == '\\'
				 && tokens[1][1] == 't')
				elog_sp_cat(&(elog_exp_replace[c]), "\t",
					    NULL);
			else
				elog_exp_with[c] = tokens[1];
		}
		free(tokens);
		++c;
	}
	elog_exp_replace[c] = NULL;
	elog_exp_with[c] = NULL;
	elog_sp_ArrFree(list);

	free(tmp);		//freeing old copy of elog_exp_ss

	//Do we want stdout?
	if (strcmp(dest, "stdout") == 0)
		elog_exp_stdout = ELOG_ERROR;	//we want stdout output
	else
		elog_exp_stdout = NULL;	//we want file output


	__exp_html_latex_do(dir, dest, elog_set_get_str("path"));
	elog_io_dir_free(dir);

	free(elog_exp_ss);
	c = 0;
	while (elog_exp_replace[c]) {
		free(elog_exp_replace[c]);
		++c;
	}
	free(elog_exp_replace);
	c = 0;
	while (elog_exp_with[c]) {
		free(elog_exp_with[c]);
		++c;
	}
	free(elog_exp_with);
	if (elog_exp_stdout)
		return elog_exp_stdout;


	return NULL;
}
